const fs = require("fs");
const { prot } = require("../../config/conifg")
const router = require('koa-router')();
module.exports = (app) => {
    const controller = querydir("./src/controllerWs");
    const api = "/ws";
    controller.forEach(item => {
        var contorFc = require("../controllerWs" + item);
        Object.keys(contorFc).forEach(key => {
            let data = contorFc[key];
            let [name, params] = data.name.split("_");
            var paramsAll = "";
            if (params) {
                paramsAll = "/:" + params
            }
            router.all(api + item + '/' + name, (ctx) => {
                var ws = ctx.websocket;
                data(ws, ctx)
            });
            console.log("websocket链接地址：");
            console.log("ws://localhost:" + prot + api + item + '/' + name);
            console.log("------end------")
        })
    })
    app.ws.use(router.routes());
    app.ws.use(router.allowedMethods());
}

//获取路径
function querydir(path) {
    var arr = [];
    let list = fs.readdirSync(path);
    list.forEach(name => {
        let dir = path + '/' + name;
        let isFile = fs.statSync(dir);
        name = name.replace(/\.js$/g, "");
        name = "/" + name
        if (name == "/index") { name = "" }
        if (isFile && isFile.isDirectory()) {
            var data = querydir(dir)
            data.forEach(item => arr.push(name + item))
        } else {
            arr.push(name)
        }
    })
    return arr;
}